package ssm.dao;

import org.apache.ibatis.annotations.*;
import ssm.domain.Permission;
import ssm.domain.Role;

import java.util.List;

public interface IRoleDao {

    @Select("select * from role where id in (select roleId from users_role where userId = #{userId})")
    /*由于此处需要根据userId查询到相应的权限，因此需要对结果进行封装*/
    @Results({
            @Result(property = "id",column = "id",id = true),
            @Result(property = "roleName",column = "roleName"),
            @Result(property = "roleDesc",column = "roleDesc"),

            @Result(property = "permissions",column = "id",javaType = java.util.List.class,
            many = @Many(select = "ssm.dao.IPermissionDao.findPermissionByRoleId"))
    })
    public List<Role> findRoleByUserId(String userId) throws Exception;

    @Select("select * from role")
    List<Role> findAll() throws  Exception;

    @Insert("insert into role(id, roleName, roleDesc) values('#',#{roleName},#{roleDesc})")
    void save(Role role);


    @Select("select * from role where id = #{id}")
    @Results({
            @Result(property = "id",column = "id",id = true),
            @Result(property = "roleName",column = "roleName"),
            @Result(property = "roleDesc",column = "roleDesc"),

            @Result(property = "permissions",column = "id",javaType = java.util.List.class,
                    many = @Many(select = "ssm.dao.IPermissionDao.findPermissionByRoleId"))
    })
    Role findById(String id);

    @Delete("delete from users_role where roleId = #{id}")
    void deleteFromUser_RoleById(String id);

    @Delete("delete from role_permission where roleId = #{id}")
    void deleteFromRole_PermissionById(String id);

    @Delete("delete from role where id = #{id}")
    void deleteRoleById(String id);

    @Select("select * from role where id = #{roleId}")
    Role findByRoleId(String roleId);

    @Select("select * from permission where id not in (select permissionId from role_permission where roleId = #{roleId})")
    List<Permission> findOtherPermissions(String roleId);

    @Insert("insert into role_permission(permissionId,roleId) values(#{permissionId},#{roleId})")
    void addPermissionToRole(@Param("roleId") String roleId, @Param("permissionId") String permissionId);
}
